Partition Array into Disjoint Intervals

  1. Partition Array into Disjoint Intervals

Given an array A, partition it into two (contiguous) subarrays left and right so that:

  • Every element in left is less than or equal to every element in right.
  • left and right are non-empty.
  • left has the smallest possible size.

Return the length of left after such a partitioning. It is guaranteed that such a partitioning exists.

Example 1:

1
2
3
Input: [5,0,3,8,6]
Output: 3
Explanation: left = [5,0,3], right = [8,6]

Example 2:

1
2
3
Input: [1,1,1,0,6,12]
Output: 4
Explanation: left = [1,1,1,0], right = [6,12]

解法1

思路:从第一个位置开始遍历数组,maxVal记录属于前left的元素中的最大值,next记录从第一个位置到目前遍历到的位置中的最大值.当出现一个比当前记录的最大值更大的元素时,比较它与next,若它大于next,则更新next.当出现一个比maxVal小的元素时,更新left的右边界,即这个比maxVal也属于left,此时,更新maxVal = next.idx = i.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int partitionDisjoint(vector<int>& A) {
if(A.empty()){
return 0;
}
int maxVal = A[0];
int next = A[0];
int idx = 0;
for(int i=1;i<A.size();++i){
next = max(A[i], next);
if(A[i] < maxVal){
maxVal = next;
idx = i;
}
}
return idx + 1;
}
};